/**
 * Created by Ysssssss on 18/11/29.
 */
import {
    encrypt,
    decrypt
} from '@common/encrypt';
import { envTarget } from '@common/environment';

const cookieVersion = '0.01';

/**
 * 设置app的详情cookie
 * @param {Object} param 参数
 */
export const setAppInfoToCookie = ({ sgId, appId, openId, storeId, platform }) => {
    const sgAppMap = {};
    const storeAppMap = {};
    const singleStoreMode = {}; // Right now singleStoreMode is only used by alipay koubei
    if (sgId) { // sgId is already encrypted
        sgAppMap[sgId] = appId;
    }
    if (storeId) { // storeId is already encrypted
        storeAppMap[storeId] = appId;
        singleStoreMode[storeId] = true;
    }
    const appOpenMap = {};
    appOpenMap[appId] = openId;
    const userSession = {};
    userSession[platform] = {
        sgAppMap: sgAppMap,
        storeAppMap: storeAppMap,
        appOpenMap: appOpenMap,
        singleStoreMode: singleStoreMode,
    };
    setCookie(`userSession${cookieVersion}`, encrypt(JSON.stringify(userSession)), 1/24);
};

/**
 * 获取app的详情
 * @param {Object} param 参数
 */
export const getAppInfoFromCookie = ({ sgId, storeId, platform }) => {
    const encryptedStr = getCookie(`userSession${cookieVersion}`);

    if (encryptedStr && (sgId || storeId)) {
        let userSession;
        let userSessionStr = decrypt(encryptedStr || '');
        if (userSessionStr) {
            try {
                userSession = JSON.parse(userSessionStr);
            } catch (e) {
                return null;
            }
        }
        if (platform && userSession[platform]) {
            const platformSession = userSession[platform];
            const sgAppMap = platformSession.sgAppMap;
            const storeAppMap = platformSession.storeAppMap;
            const appOpenMap = platformSession.appOpenMap;
            const singleStoreMode = platformSession.singleStoreMode;
            let appId = '';
            if (storeId && singleStoreMode[storeId]) { // 如果传入了storeId并且store工作在独立模式中，则使用storeId计算appId
                appId = storeAppMap && storeAppMap[storeId];
            }
            if (!appId && sgId) { // 如果appId没有计算出来，并且sgId存在，则使用sgId计算appId
                appId = sgAppMap && sgAppMap[sgId];
            }
            const openId = appOpenMap && appOpenMap[appId];

            if (appId && openId) {
                return {
                    appId: appId,
                    openId: openId,
                    singleStoreMode: (singleStoreMode && !!singleStoreMode[storeId]) || false,
                };
            }
        }
    }

    return null;
};

/**
 * 设置默认的cookie
 * @param {String} name 名字
 * @param {Any} value 值
 * @param {Number} days 时间：天
 */
export const setNormalCookie = (name, value, days) => {
    if(!days){
        days = 30;
    }
    const expiresTimes = new Date(Date.now() + days * 86400000);
    document.cookie = `${name}=${value}; path=/; expires=${expiresTimes}`;
};

/**
 * 设置cookie
 * @param {String} name 名字
 * @param {Any} value 值
 * @param {Number} days 时间：天
 */
export const setCookie = (name, value, days) => {
    const scene = envTarget();
    if(!days){
        days = 30;
    }
    const expiresTimes = new Date(Date.now() + days * 86400000);
    document.cookie = `${scene+name}=${value}; path=/; expires=${expiresTimes}`;
};

/**
 * 获取默认的cookie值
 * @param {String} name 名字
 */
export const getNormalCookie = (name) => {
    const cookieString = '; ' + document.cookie;
    const cookies = cookieString.split( '; ' + name + '=' );
    if ( cookies.length === 2 ){
        return cookies.pop().split( ';' ).shift();
    }
    return null;
};

/**
 * 获取cookie
 * @param {String} name 名字
 */
export const getCookie = (name) => {
    const scene = envTarget();
    const cookieString = '; ' + document.cookie;
    const cookies = cookieString.split( '; ' + scene + name + '=' );
    if ( cookies.length === 2 ){
        return cookies.pop().split( ';' ).shift();
    }
    return null;
};
